import { AtRate, AtTextarea, AtImagePicker } from 'taro-ui'
import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components'
import classnames from 'classnames'
import cloneDeep from 'lodash/cloneDeep'
import { create, getEvaluateGoodsList } from '@/api/order/evaluate'
import { IS_USERINFO } from '@/store/user/action-types'
import CryptoJS from 'crypto-js'


import './index.scss'
const domain: string = `${BASE_API_URL}`
const getByteLen = (val: any) => {
    let len = 0
    if (!val) {
        len = 0
    } else {
        for (let i = 0; i < val.length; i++) {
            if (String(val[i]).match(/[^\x00-\xff]/gi) !== null) {
                len += 3
            } else {
                len += 1
            }
        }
    }
    return len.toString()
}

type State = {
    attitudeGrade: number
    efficiencyGrade: number
    qualityGrade: number
    goodsList: any
    orderInfo: any
    files: any
    value: ''
    evalualteList: Array<any>
    tipVisible: boolean
    giftVisible: boolean
    giftContent: any
}
export default class Index extends Component<any, State> {
    $instance = getCurrentInstance();

    constructor(props) {
        super(props)
        this.state = {
            attitudeGrade: 5,// 态度评分
            efficiencyGrade: 5,// 效率评分
            qualityGrade: 5,// 质量评分
            goodsList: [],
            orderInfo: [],
            value: '',
            files: [],
            evalualteList: [],
            tipVisible: false,
            giftVisible: false,
            giftContent: {
                remark: '',
                value: '',
                title: ''
            },
        }
    }

    componentDidMount() {

        this.initPage()
    }

    async initPage() {
        Taro.showLoading({
            title: '加载中'
        })
        const { orderNumber } = this.$instance.router.params
        getEvaluateGoodsList({
            orderNumber,
        }).then(res => {
            const { data } = res.data
            this.setState({
                goodsList: data.goodsItems,
                orderInfo: data.orderInfo
            }, () => {
                this.initEvalualteList()
            })
            Taro.hideLoading()

        })
    }

    // 设置态度评分
    handleChangeAttitudeGrade(attitudeGrade) {
        this.setState({
            attitudeGrade
        })
    }

    // 设置效率评分
    handleChangeEfficiencyGrade(efficiencyGrade) {
        this.setState({
            efficiencyGrade
        })
    }

    // 设置质量评分
    handleChangeQualityGrade(qualityGrade) {
        this.setState({
            qualityGrade
        })
    }

    initEvalualteList() {
        const { goodsList } = this.state
        let evalualteList: Array<any> = []
        goodsList.map((i, index) => {
            evalualteList.push({
                goodsId: i.goodsId,
                goodsName: i.goodsName,
                goodsThumbnail: i.goodsThumbs,
                goodsCode: i.goodsCode,
                isHide: index === 0 ? false : true,
                btnText: '评价',
                goodsGrade: 5,
                commentContent: '',
                imgids: []
            })
        })
        this.setState({
            evalualteList
        })
    }
    handleChangeGoodsGrade(index, value) {
        let { evalualteList } = this.state
        let item = cloneDeep(evalualteList[index])
        item.goodsGrade = Number(value)
        evalualteList[index] = item
        this.setState({
            evalualteList
        })
    }

    handleChangeCommentContent(index, value) {
        let { evalualteList } = this.state
        let item = cloneDeep(evalualteList[index])
        item.commentContent = value
        item.btnText = value.trim() ? '已评价' : '评价'
        evalualteList[index] = item
        this.setState({
            evalualteList
        })
    }

    handleChangeHide(activeIndex) {
        let { evalualteList } = this.state
        let cloneEvalualteList = cloneDeep(evalualteList)
        cloneEvalualteList = cloneEvalualteList.map((i, index) => {
            if (index !== activeIndex) {
                i.isHide = true
            }
            return i
        })
        let item = cloneEvalualteList[activeIndex]
        item.isHide = !item.isHide
        cloneEvalualteList[activeIndex] = item
        this.setState({
            evalualteList: cloneEvalualteList
        })
    }

    handleClose() {
        this.setState({
            tipVisible: false
        })
    }

    // 点击提交
    handleSubmit() {
        const { evalualteList } = this.state
        console.log('evalualteList', evalualteList)
        let checked = this.checkConmentLen(evalualteList)
        if (!checked) {
            this.setState({
                tipVisible: true
            })
            return
        }
        this.handleSubmitEval()

    }

    async handleSubmitEval() {
        const { orderNumber } = this.$instance.router.params
        const { attitudeGrade, efficiencyGrade, qualityGrade, evalualteList } = this.state
        let list = evalualteList.map(i => {
            let imgids = []
            if (i.imgids.length > 0) {
                i.imgids.forEach((val) => {
                    imgids.push(val.id)
                });
            }
            return {
                goodsId: i.goodsId,
                commentContent: i.commentContent,
                goodsGrade: i.goodsGrade,
                goodsCode: i.goodsCode,
                imgids: imgids.join(',')
            }
        })
        let res = await create({
            orderNumber,
            attitudeGrade,
            efficiencyGrade,
            qualityGrade,
            list
        })

        const { data } = res.data
        if (data.isHasRedPacket) {
            this.setState({
                giftContent: data,
                giftVisible: true
            })
        } else {
            await Taro.showToast({
                title: '已评价',
                icon: 'success',
                duration: 1500
            })
            Taro.navigateBack({
                delta: 1
            })
        }
    }

    checkConmentLen(evalualteList) {
        let checked = false
        evalualteList.map(i => {
            if (String(i.commentContent).trim().length > 10 || i.imgids.length > 0) {
                checked = true
            }
        })
        return checked
    }

    /*上传图片
    index 当前商品index
    files 上传图片数组
    type 操作 add 为添加 remove为删除
    reIndex 删除的index
    */

    async onFiles(index, files, type, reIndex) {
        const { evalualteList, orderInfo } = this.state
        const obj = await this.getAuth()
        if (files.length > 9) {
            return Taro.showToast({
                title: '已经添加9张了',
                icon: 'none',
                // mask: true,
                // duration: 10000
            })
        }
        // 添加上传图片
        if (type == 'add') {
            //启动上传等待中...
            Taro.showToast({
                title: '正在上传...',
                icon: 'loading',
                mask: true,
                duration: 10000
            })
            let uploadImgCount = 0;
            for (let i = 0, h = files.length; i < h; i++) {
                Taro.uploadFile({
                    url: domain + `/v1/upload/create`,
                    filePath: files[i].url,
                    name: 'file',
                    formData: {
                        'act': 73,
                        'fields': '*',
                        'relatedCode': orderInfo.orderNumber
                    },
                    header: {
                        "Content-Type": "multipart/form-data",
                        'Authorization': obj['Authorization'],
                        'Entity-Date': obj['Entity-Date'],
                        'Entity-Length': obj['Entity-Length'],
                        // 'str': obj['str'],
                        // 'accessKey': obj['accessKey'],
                    },
                    success: (res) => {
                        uploadImgCount++;
                        var data = JSON.parse(res.data);
                        const { data: { id } } = data
                        evalualteList[index].imgids = files
                        evalualteList[index].imgids[i]['id'] = id
                        this.setState({
                            evalualteList
                        })
                        //如果是最后一张,则隐藏等待中
                        if (uploadImgCount == files.length) {
                            Taro.hideToast();
                        }
                    },
                    fail: function (res) {
                        console.log('res: ', res);
                        Taro.hideToast();
                        Taro.showModal({
                            title: '错误提示',
                            content: '上传图片失败',
                            showCancel: false,
                            success: function (res) { }
                        })
                    }
                });
            }
        } else if (type == 'remove') {
            // 删除操作
            evalualteList[index].imgids.splice(reIndex, 1)
            this.setState({
                evalualteList
            })
        }
    }

    getAuth() {
        const USERINFO = Taro.getStorageSync(IS_USERINFO)
        let { accessId, accessKey, serverTime } = USERINFO
        let entityLength: string = '0'
        let clientTime = Date.parse(new Date()['toGMTString']()) / 1000

        if (/^P(OST|UT)$/.test('POST')) {
            entityLength = getByteLen({})
        }

        let clientTimeStamp = typeof clientTime === 'number' ? clientTime : 0
        if (!clientTimeStamp) {
            let date = new Date()['toGMTString']()
            clientTimeStamp = Date.parse(date) / 1000// 客户端时间戳
            clientTime = clientTimeStamp
        }
        let serverTimeStamp = serverTime

        // 时间差的处理
        let difTimestamp = Number(serverTimeStamp) - Number(clientTimeStamp)// 客户端时间与服务器时间差
        let clientCorrectTimeStamp = +new Date() / 1000 + difTimestamp// 当下正确时间戳
        clientTime = new Date(clientCorrectTimeStamp * 1000)['toGMTString']()// 当下正确时间
        let str = 'POST' + '\\n' + 'v1/upload/create' + '\\n' + entityLength + '\\n' + clientTime
        let hash = CryptoJS.HmacSHA1(str, accessKey)
        let sha = hash.toString(CryptoJS.enc.Base64)
        let auth = 'Jekun ' + accessId + ':' + sha
        return {
            'Authorization': auth,
            'Entity-Date': clientTime,
            'Entity-Length': entityLength,
            'str': str,
            'accessKey': accessKey.substring(accessKey.length - 10)
        }
    }

    //预览评价图片
    previewImage(urls, index) {
        let arr = []
        urls.forEach((val) => {
            arr.push(val.url)
        });
        Taro.previewImage({
            current: arr[index], // 当前显示图片的http链接
            urls: arr, // 需要预览的图片http链接列表
        })
    }

    render() {
        let { evalualteList, tipVisible, giftVisible, giftContent, files } = this.state
        // 总服务评价
        let serviceEvaluateView = <View className="service-evaluation">
            <View className="evaluation-text">
                <text >服务评价</text>
            </View>
            <View className="evaluation-item">
                <text>态度评分</text>
                <View className="evaluation-stars">
                    <AtRate
                        size={24}
                        value={this.state.attitudeGrade}
                        onChange={this.handleChangeAttitudeGrade.bind(this)}
                    />
                </View>
            </View>
            <View className="evaluation-item">
                <text>效率评分</text>
                <View className="evaluation-stars">
                    <AtRate
                        size={24}
                        value={this.state.efficiencyGrade}
                        onChange={this.handleChangeEfficiencyGrade.bind(this)}
                    />
                </View>
            </View>
            <View className="evaluation-item">
                <text>质量评分</text>
                <View className="evaluation-stars">
                    <AtRate
                        size={24}
                        value={this.state.qualityGrade}
                        onChange={this.handleChangeQualityGrade.bind(this)}
                    />
                </View>
            </View>
        </View>

        // 底部提交按钮
        let submitBtnView = <View className="submit-wrap" onClick={this.handleSubmit.bind(this)}>
            <View className='submit'>提交</View>
        </View>

        let submitTipDialogView = <View className='submit-tip-dialog'>
            <View className='content'>
                <View className='mask' onClick={this.handleClose.bind(this)}></View>
                <View className='content-wrap'>
                    <View className='content-wrap-h'>
                        温馨提示
                    </View>
                    <View className='content-wrap-tips'>
                        填写10个文字或上传图片即可获得红包
                    </View>
                    <View className='content-wrap-action'>
                        <View onClick={this.handleSubmitEval.bind(this)} className='content-wrap-action-btn'>
                            不需要了，继续提交
                        </View>
                    </View>
                </View>
            </View>
        </View>

        let giftView = <View className='redpack-dialog'>
            <View className='content'>
                <View className='mask'></View>
                <View className='content-wrap'>
                    <View className='content-wrap-h'>
                        <Text className='text'>{giftContent.title}</Text>
                    </View>
                    <View className='content-wrap-tips'>
                        <Text className='amount'>{giftContent.value}</Text>
                        <Text className='date'>{giftContent.remark}</Text>
                    </View>
                    <View className='content-wrap-action'>
                        <View onClick={() => {
                            Taro.switchTab({
                                url: '/pages/tabbar/index/index'
                            })
                        }} className='content-wrap-action-btn'>
                            去使用
                        </View>
                    </View>
                </View>
            </View>
        </View>
        return (
            <View className="bg">
                { tipVisible && submitTipDialogView}
                { giftVisible && giftView}
                { submitBtnView}
                { serviceEvaluateView}
                {/** 评价商品 */}
                <View className="evaluation-goods">
                    {evalualteList.length && evalualteList.map((i, index) => {
                        return (
                            <View className="evaluation-goods-item" key={i.goodsId + index}>
                                <View className="good-info">
                                    {
                                        i.goodsThumbnail &&
                                        <View className="good-img">
                                            <Image
                                                className='img'
                                                mode='aspectFill'
                                                lazyLoad
                                                src={i.goodsThumbnail} />
                                        </View>

                                    }
                                    <View className="desc">
                                        <Text className="goods-name">
                                            {i.goodsName}
                                        </Text>
                                        {/* <View className="tags"></View> */}
                                    </View>
                                </View>
                                <View className="goods-grade">
                                    <View className="left">
                                        <Text className='title'>商品评分</Text>
                                        <View className="evaluation-stars">
                                            <AtRate
                                                size={24}
                                                value={this.state.evalualteList[index].goodsGrade}
                                                onChange={this.handleChangeGoodsGrade.bind(this, index)}
                                            />
                                        </View>
                                    </View>
                                    <View className="rigth">
                                        <View className={
                                            classnames('btn', {
                                                'active': String(i.commentContent).trim()
                                            })
                                        } onClick={this.handleChangeHide.bind(this, index)}>{i.btnText}</View>
                                    </View>
                                </View>
                                {!this.state.evalualteList[index].isHide &&
                                    <View className="goods-textarea">
                                        <AtTextarea
                                            className='area'
                                            value={this.state.evalualteList[index].commentContent}
                                            onChange={this.handleChangeCommentContent.bind(this, index)}
                                            maxLength={200}
                                            placeholder='评价内容超过10个字就有机会获得红包'
                                        />
                                    </View>
                                }
                                {/* 评价晒单 */}
                                <View className="goods-picture">
                                    <Text className='title'>添加晒单（{i.imgids.length}/9）</Text>
                                    <AtImagePicker
                                        className="goods-picture-AtImagePicker"
                                        multiple
                                        count={9}
                                        length={9}
                                        showAddBtn={i.imgids.length < 9}
                                        files={i.imgids}
                                        onChange={this.onFiles.bind(this, index)}
                                        onImageClick={(index) => this.previewImage(i.imgids, index)}
                                    />
                                </View>
                            </View>
                        )
                    }
                    )}
                </View>
            </View>
        )
    }
}
